package com.hh.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/*跨域配置（全局CORS配置）  为所有控制器统一配置  跨域访问  就不用一个一个改了*/
// 对 options 预检请求、跨域等 进行规则判断。
@Configuration
public class CrosConfig {
    /*设置允许跨域的源*/
    private String[] originsVal = new String[]{
            "127.0.0.1:8080",
            "localhost:8080",
            "116.62.224.134:8080",
            "116.62.224.134",
            "www.myhaohao.top:8080",
            "www.myhaohao.top",
            "myhaohao.top:8080",
            "myhaohao.top",
            "myhaohao.top:8081"
    };

    /*跨域过滤器*/
    @Bean
    public CorsFilter corsFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        //创建CorsConfiguration对象后添加配置
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        /*添加允许跨域的源   设置放行哪些原始域*/
        //        corsConfiguration.addAllowedOrigin("*");
        addAllowedOrigins(corsConfiguration);

        //放行哪些原始请求头部信息
        corsConfiguration.addAllowedHeader("*");

        //暴露哪些头部信息
//        corsConfiguration.addExposedHeader("*");

        //放行哪些请求方式  (这里是放行全部)
//        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addAllowedMethod("GET");     //get
        corsConfiguration.addAllowedMethod("PUT");     //put
        corsConfiguration.addAllowedMethod("POST");    //post
        corsConfiguration.addAllowedMethod("DELETE");  //delete
        corsConfiguration.addAllowedMethod("PATCH");  //patch

        // 对于 非简单请求  传送证书（不然这些请求会有 跨域问题）
        corsConfiguration.setAllowCredentials(true);

        //是否发送Cookie
//        corsConfiguration.setAllowCredentials(true);

        //2. 添加映射路径
        source.registerCorsConfiguration("/**", corsConfiguration);
        // 返回CorsFilter
        return new CorsFilter(source);
    }

    /**
     * 给 cors配置 添加允许访问的 跨域源   (读取已有的字符串数组里的ip地址及端口)
     * @param corsConfiguration
     */
    private void addAllowedOrigins(CorsConfiguration corsConfiguration){
        /*http  和 https 都设置允许*/
        for (String origin : originsVal) {
            corsConfiguration.addAllowedOrigin("http://" + origin);
            corsConfiguration.addAllowedOrigin("https://" + origin);
        }
    }
}
